package com.atguigu.gmall.item;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.list.client.ListFeignClient;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.product.model.*;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@RestController
@RequestMapping("/api/item")
@SuppressWarnings("all")
public class ItemController {
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private Executor executor;
    @Autowired
    private ListFeignClient listFeignClient;


    /**
     * 提供给前端服务调用RestFul接口实现,汇总商品详情页所需7项数据
     *
     * @param skuId - **skuInfo**：当前商品SKU信息包含SKU图片列表
     *              - **categoryView**：当前商品所属的分类信息（包含三级）
     *              - **price**：当前商品最新价格
     *              - **spuPosterList**：当前商品海报图片集合
     *              - **skuAttrList**：当前商品平台属性及属性值集合--- 规格与参数
     *              - **spuSaleAttrList**：当前商品销售属性集合选中效果
     *              - **valuesSkuJson**：切换SKU转换SKU商品json字符串信息
     * @return
     */
    @GetMapping("/{skuId}")
    public Result getItemAllData(@PathVariable("skuId") Long skuId) {

//        //判断用户访问商品不存在  说明是非法访问,直接返回 返回执行远程  todo : 测试布隆过滤器
//        RBloomFilter<Long> bloomFilter = redissonClient.getBloomFilter(RedisConst.SKU_BLOOM_FILTER);
//        boolean contains = bloomFilter.contains(skuId);
//        if (!contains){
//            throw new RuntimeException("访问数据不存在");
//        }
        HashMap<String, Object> data = new HashMap<>();

        CompletableFuture<SkuInfo> skuInfocCompletableFuture = CompletableFuture.supplyAsync(() -> {
            //1.远程调用商品服务-根据skuID查询商品sku信息
            SkuInfo skuInfo = productFeignClient.getSkuInfoAndImage(skuId);
            if (skuInfo != null) {
                data.put("skuInfo", skuInfo);
            }
            return skuInfo;




        },executor);

        CompletableFuture<Void> categoryViewFuture = skuInfocCompletableFuture.thenAcceptAsync(skuInfo -> {
            //2.根据三级分类id获取分类信息
            BaseCategoryView categoryView = productFeignClient.getCategoryView(skuInfo.getCategory3Id());
            if (categoryView != null) {
                data.put("categoryView", categoryView);
            }
        },executor);
        CompletableFuture<Void> priceFuture = CompletableFuture.runAsync(() -> {
            //3.根据skuId 获取最新的商品价格
            BigDecimal price = productFeignClient.getSkuPrice(skuId);
            if (price != null) {
                data.put("price", price);
            }

        },executor);
        CompletableFuture<Void> spuPosterListFuture = skuInfocCompletableFuture.thenAcceptAsync((skuInfo) ->
        {
            //4.根据spuId 获取海报数据
            List<SpuPoster> spuPosterList = productFeignClient.findSpuPosterBySpuId(skuInfo.getSpuId());
            if (!CollectionUtils.isEmpty(spuPosterList)) {
                data.put("spuPosterList", spuPosterList);
            }

        },executor);

        CompletableFuture<Void> attrListFuture = CompletableFuture.runAsync(() -> {
            //5.根据skuId 获取平台属性数据
            List<BaseAttrInfo> attrList = productFeignClient.getAttrList(skuId);
            if (!CollectionUtils.isEmpty(attrList)) {
                data.put("skuAttrList", attrList);
            }

        }, executor);
        CompletableFuture<Void> spuSaleAttrListFuture = skuInfocCompletableFuture.thenAcceptAsync((skuInfo) -> {
            //6.根据spuId,skuId 获取销售属性数据
            List<SpuSaleAttr> spuSaleAttrList = productFeignClient.getSpuSaleAttrListCheckBySku(skuId, skuInfo.getSpuId());
            if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
                data.put("spuSaleAttrList", spuSaleAttrList);
            }

        },executor);
        CompletableFuture<Void> valuesSkuJsonFuture = skuInfocCompletableFuture.thenAcceptAsync(skuInfo -> {
            //7.根据spuId 获取到销售属性值Id 与skuId 组成的数据集
            Map<String, String> valuesSkuJson = productFeignClient.getSkuValueIdsMap(skuInfo.getSpuId());
            if (!CollectionUtils.isEmpty(valuesSkuJson)) {
                data.put("valuesSkuJson", JSON.toJSONString(valuesSkuJson));
            }
        },executor);
        //8.TODO 远程调用搜索微服务更新商品热度
        CompletableFuture<Void> goodsScoreCompletableFuture = CompletableFuture.runAsync(() -> {
            listFeignClient.innerScore(skuId);
        }, executor);

        CompletableFuture.allOf(
                skuInfocCompletableFuture,
                categoryViewFuture,
                spuPosterListFuture,
                attrListFuture,
                spuSaleAttrListFuture,
                valuesSkuJsonFuture,
                priceFuture,
                goodsScoreCompletableFuture
        ).join();
        return Result.ok(data);
    }


}
